﻿class FileDownloader {
    constructor(options = {}) {
        this.apiBase = options.apiBase || '/api/files';
        this.timeout = options.timeout || 30000;
    }

    /**
     * 下载文件
     * @param {string} pound_no 文件ID
     * @param {string} guid 文件名（可选）
     * @param {string} certi_no 安全令牌（可选）
     * @param {object} options 额外选项
     */


    async download(pound_no, guid = '', certi_no = '', options = {}) {
        const {
            method = 'GET',
            showProgress = true,
            checkWeChat = true
        } = options;

        try {
            // 检测微信环境
            const isWeChat = checkWeChat && this.isWeChatBrowser();

          


            if (isWeChat)
            {
                console.log("isWeChat" + isWeChat);
                return await this.downloadInWeChat(pound_no, guid, certi_no);
            }
            else
            {
                console.log("isWeChat" + isWeChat);

                return await this.downloadInBrowser(pound_no, guid, certi_no, method, showProgress);
            }
        } catch (error) {
            this.showError('下载失败: ' + error.message);
            throw error;
        }
    }



    /**
    * 预览文件
    * @param {string} pound_no 文件ID
    * @param {string} guid 文件名（可选）
    * @param {string} certi_no 安全令牌（可选）
    * @param {object} options 额外选项
    */
    async viewload(pound_no, guid = '', certi_no = '', options = {}) {
        const {
            method = 'GET',
            showProgress = true,
            checkWeChat = true
        } = options;

        try {
            // 检测微信环境
            const isWeChat = checkWeChat && this.isWeChatBrowser();




            const params = new URLSearchParams();
            params.append('pound_no', pound_no);
            if (guid) params.append('guid', guid);
            if (certi_no) params.append('certi_no', certi_no);

            const viewloadUrl = `${this.apiBase}/viewload?${params}`;


            console.log("1---------------------" + viewloadUrl);

            //微信环境中直接打开新窗口
            const newWindow = window.open(viewloadUrl, '_blank');

            console.log("2---------------------");
            if (!newWindow || newWindow.closed) {
                console.log("3---------------------");

                // 如果弹窗被阻止，显示引导提示
                this.showWeChatGuide(viewloadUrl, guid);
                return { success: false, method: 'WeChat_Guide' };
            }

            console.log("9---------------------");

            return { success: true, method: 'WeChat_NewWindow' };



          
        } catch (error) {
            this.showError('下载失败: ' + error.message);
            throw error;
        }
    }








    /**
     * 在普通浏览器中下载
     */
    async downloadInBrowser(pound_no, guid, certi_no, method = 'GET', showProgress = true) {
        const params = new URLSearchParams();
        params.append('pound_no', pound_no);
        if (guid) params.append('guid', guid);
        if (certi_no) params.append('certi_no', certi_no);

        let url = `${this.apiBase}/download?${params}`;

        console.log("method.toUpperCase():[" + method.toUpperCase() + "]");
        if (method.toUpperCase() === 'GET')
        {
            
            // GET请求直接下载
            this.triggerDownload(url, guid);
            return { success: true, method: 'GET' };
        } else
        {
            // POST请求处理
            const response = await this.fetchWithProgress(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ pound_no, guid, certi_no })
            }, showProgress);

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || '下载失败');
            }

            await this.handleFileResponse(response, guid);
            return { success: true, method: 'POST' };
        }
    }

    /**
     * 在微信环境中下载
     */
   

    async downloadInWeChat(pound_no, guid, certi_no) {
        const params = new URLSearchParams();
    params.append('pound_no', pound_no);
    if (guid) params.append('guid', guid);
    if (certi_no) params.append('certi_no', certi_no);

        const downloadUrl = `${this.apiBase}/download?${params}`;

        console.log("1---------------------" + downloadUrl);

        //微信环境中直接打开新窗口
        const newWindow = window.open(downloadUrl, '_blank');

        console.log("2---------------------" );
        if (!newWindow || newWindow.closed)
        {
            console.log("3---------------------");

            // 如果弹窗被阻止，显示引导提示
            this.showWeChatGuide(downloadUrl, guid);
            return { success: false, method: 'WeChat_Guide' };
        }

        console.log("9---------------------");

        return { success: true, method: 'WeChat_NewWindow' };
    }

    /**
     * 带进度条的fetch请求
     */
    async fetchWithProgress(url, options = {}, showProgress = true) {
        const response = await fetch(url, options);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const contentLength = response.headers.get('Content-Length');
        const total = parseInt(contentLength, 10);

        if (!showProgress || !total) {
            return response;
        }

        let loaded = 0;
        const reader = response.body.getReader();
        const stream = new ReadableStream({
            start(controller) {
                function push() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            controller.close();
                            return;
                        }
                        loaded += value.length;
                        //updateProgress(loaded, total);

                        const percent = total ? (loaded / total * 100).toFixed(1) : 0;
                        console.log(`Download Progress: ${percent}%`);


                        controller.enqueue(value);
                        push();
                    });
                }
                push();
            }
        });

        return new Response(stream, {
            headers: response.headers
        });
    }

    /**
     * 处理文件响应
     */
    async handleFileResponse(response, guid) {
        // 获取文件名
        const contentDisposition = response.headers.get('Content-Disposition');
        let finalguid = guid || `download_${Date.now()}.pdf`;

        if (contentDisposition) {
            let match = contentDisposition.match(/guid\*=utf-8''([^;]+)/i);
            if (match) {
                finalguid = decodeURIComponent(match[1]);
            } else {
                match = contentDisposition.match(/guid=([^;]+)/i);
                if (match) {
                    finalguid = match[1].trim().replace(/^"|"$/g, '');
                }
            }
        }

        // 创建Blob并下载
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        this.triggerDownload(url, finalguid);
        window.URL.revokeObjectURL(url);
    }

    /**
     * 触发下载
     */
    triggerDownload(url, guid)
    {
      //  alert("url:" + url);
        const a = document.createElement('a');
        a.href = url;
        a.download = guid;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    /**
     * 显示微信引导提示
     */
    showWeChatGuide(downloadUrl, guid) {
        const guideHtml = `
            <div id="wechat-download-guide" style="
                position: fixed; top: 0; left: 0; right: 0; bottom: 0; 
                background: rgba(0,0,0,0.8); z-index: 10000; 
                display: flex; align-items: center; justify-content: center;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            ">
                <div style="
                    background: white; padding: 30px; border-radius: 12px; 
                    max-width: 90%; width: 400px; text-align: center;
                    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                ">
                    <h3 style="margin: 0 0 15px 0; color: #333; font-size: 18px;">
                        📎 文件下载提示
                    </h3>
                    <p style="margin: 0 0 20px 0; color: #666; line-height: 1.5; font-size: 14px;">
                        由于微信限制，请按以下步骤下载文件：
                    </p>
                    <ol style="text-align: left; margin: 0 0 20px 0; padding-left: 20px; color: #555;">
                        <li style="margin-bottom: 8px;">点击右上角 <strong>•••</strong> 按钮</li>
                        <li style="margin-bottom: 8px;">选择 <strong>"在浏览器中打开"</strong></li>
                        <li style="margin-bottom: 8px;">在浏览器中重新下载文件</li>
                    </ol>
                    <div style="margin: 20px 0;">
                        <a href="${downloadUrl}" download="${guid}" 
                           style="display: inline-block; padding: 12px 24px; 
                                  background: #07c160; color: white; 
                                  text-decoration: none; border-radius: 6px;
                                  font-size: 14px; font-weight: 500;">
                            📥 尝试下载文件
                        </a>
                    </div>
                    <button onclick="document.getElementById('wechat-download-guide').remove()" 
                            style="padding: 8px 16px; background: #f0f0f0; 
                                   border: none; border-radius: 4px; 
                                   color: #666; cursor: pointer; font-size: 13px;">
                        关闭提示
                    </button>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', guideHtml);
    }

    /**
     * 检测微信浏览器
     */
    isWeChatBrowser() {
        return /MicroMessenger/i.test(navigator.userAgent);
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        // 可以使用Toast、Alert等方式显示错误
        alert(message);
        console.error('Download Error:', message);
    }

    /**
     * 更新进度条
     */
    updateProgress(loaded, total) {
        const percent = total ? (loaded / total * 100).toFixed(1) : 0;
        console.log(`Download Progress: ${percent}%`);
        // 可以在这里更新UI进度条
    }
}

// 创建全局实例
window.fileDownloader = new FileDownloader();